#include <iostream>
#include <mutex>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "Mutex.hpp"
using namespace MutexModule;
int ticket = 1000;
class ThreadData
{
public:
    ThreadData(const std::string &n, Mutex &lock)
        : name(n),
          lockp(&lock)
    {
    }
    ~ThreadData() = default;

    std::string name;
    Mutex *lockp;
};
void *routine(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    while (1)
    {
        usleep(1000);
        {
            LockGuard guard(*td->lockp);
            if (ticket > 0)
            {
                usleep(1000);
                printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
                ticket--;
            }
            else
            {
                break;
            }
            usleep(500);
        }
    }
    return nullptr;
}
int main()
{
    int a = 10;
    Mutex lock;
    pthread_t tid1, tid2, tid3, tid4;
    ThreadData *t1 = new ThreadData("thread-1", lock);
    ThreadData *t2 = new ThreadData("thread-2", lock);
    ThreadData *t3 = new ThreadData("thread-3", lock);
    ThreadData *t4 = new ThreadData("thread-4", lock);
    pthread_create(&tid1, nullptr, routine, t1);
    pthread_create(&tid2, nullptr, routine, t2);
    pthread_create(&tid3, nullptr, routine, t3);
    pthread_create(&tid4, nullptr, routine, t4);

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    return 0;
}